package com.lipaluma.field.validator.impl.generic;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.lipaluma.context.Context;
import com.lipaluma.field.validator.Resetable;
import com.lipaluma.field.validator.ValidationError;
import com.lipaluma.field.validator.Validator;
import com.lipaluma.xml.validator.XmlValidator;

/**
 * Check if the entry value is unique
 * <p>
 * <p>
 * For Initialisation :
 * <ul>
 * 	<li>
 * 	<u><b>By annotations :</b></u> Use the annotation of validation corresponding to the type of the field and
 * put at true the <code>unique</code> attribute.
 * </li>
 * 	<li>
 * 	<u><b>By Xml :</b></u>
 * Just add the attribute <code>unique</code> on the toMap element like below : <br/>
 * <code>
 * &lt;ToMap field="..." <b>unique=""</b>  .../><br/>
 * </code>
 * Just the presence of the attribute is suficient to activate the validation
 * </li>
 * </ul>
 * @author Mario
 *
 */
public abstract class AbstractUniqueValidator implements Validator, Resetable {

	private Set<Object> encounteredValues = new HashSet<Object>();
	
	public boolean init(Context context, Field field, XmlValidator element) {
		return true;
	}
	
	public boolean validate(Object value, List<ValidationError> errors) {
		if(!encounteredValues.add(value)) {
			errors.add(new ValidationError("The value "+value+" is already encountered and must be unique"));
			return false;
		}
		return true;
	}

	@Override
	public void reset() {
		encounteredValues.clear();
	}
}
